package com.sq.partner.manager.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.ActirationErrorInfo;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.dao.INlifePlanDao;
import com.sq.partner.manager.mybatis.model.CommamtFee;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.FacadeNewPayment;
import com.sq.partner.manager.mybatis.model.FacadePayment;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.OutboundCardApply;
import com.sq.partner.manager.service.ExternalPaymentCardService;
import com.sq.partner.manager.service.OutboundCardApplyService;
import com.sq.partner.manager.service.OutboundNewPayService;
import com.sq.partner.manager.service.PayService;
import com.sq.partner.manager.service.impl.NlifePlanConfigServiceImpl;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.SqlUtil;
import com.sq.partner.manager.util.StrUtil;

/**
 * 激活卡申请出库
 * 
 * SQ
 *
 */
@Controller
@RequestMapping(value = "/outboundCard")
public class OutboundCardApplyController {

    private static Logger logger = LogUtil
            .getLog(NlifePlanConfigServiceImpl.class);

    @Resource
    private OutboundCardApplyService outboundCardApplyService;
    @Resource
    private OutboundNewPayService outboundNewPayService;
    @Resource
    private INlifePlanDao nlifePlanDao;
    @Resource
    private PayService payService;
    @Resource
    private ExternalPaymentCardService cardService;

    /**
     * 激活卡出库
     * 
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/outbound")
    public String outbound(HttpServletRequest request) throws Exception {
        request.setAttribute("flag", null);
        return "actirationCard/outboundApply/outbound";
    }

    /**
     * 根据条件查询出库结果
     * 
     * @param session
     * @param page
     * @param name
     *            卡名称
     * @param cardNo卡号
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryOutboundList", method = RequestMethod.POST)
    @ResponseBody
    public Page<OutboundCardApply> queryApplyList(HttpSession session,
            Page<OutboundCardApply> page, String name) throws Exception {
        // 初始化分页信息
        Map<String, Object> paramMap = SqlUtil.buildPageMap(page);
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        // String deptNo=gatewayuser.getDepartmentStr();
        // deptNo = "(" + deptNo + ")";
        String deptNo = gatewayuser.getUserComcode();
        if(StrUtil.isNotEmpty(name)){
            paramMap.put("name", name);
        }
        // 状态为库存的卡单
        paramMap.put("status", Constants.ACTIR_CARD_STOCK);
        paramMap.put("deptNo", deptNo);
        page.setMap(paramMap);
        page = outboundCardApplyService.queryOutboundList(page);
        return page;
    }

    /**
     * 跳转至方案关联页面
     * 
     * @param model
     * @param name
     * @param cardNo
     * @param count
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/outboundApply")
    public String outboundCardApply(ModelMap model, HttpSession session,
            String cardDefineId, String cardNo, String count, String premAmt,
            String pricelessType, String planNo, String prodCode) throws Exception {
        BigDecimal premAmtInt = new BigDecimal(premAmt);
        BigDecimal countInt = new BigDecimal(count);
        
        BigDecimal totalPrem = premAmtInt.multiply(countInt);
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        totalPrem = new BigDecimal(decimalFormat.format(totalPrem));
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        // name=URLDecoder.decode(name,"utf-8");
        // name=new String(name.getBytes("ISO8859-1"), "UTF-8");
        model.put("cardDefineId", cardDefineId);
        model.put("name", session.getAttribute("cardDefineName"));
        model.put("cardNo", cardNo);
        model.put("count", count);
        model.put("status", Constants.ACTIR_CARD_STOCK);
        model.put("deptName", session.getAttribute("deptName"));
        model.put("deptNo", gatewayuser.getUserComcode());
        model.put("totalPrem", totalPrem);
        model.put("premAmt", premAmtInt);
        model.put("pricelessType", pricelessType);
        model.put("planNo", planNo);
        model.put("planName", session.getAttribute("planName"));
        model.put("prodCode", prodCode);
        // 加载数据字典信息
        outboundCardApplyService.loadDictData(model);

        return "actirationCard/outboundApply/relatedPlan";
    }

    /**
     * 查询待出卡单信息
     * 
     * @param model
     * @param name
     * @param cardNo
     * @param count
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/outboundCardList")
    @ResponseBody
    public Page<OutboundCardApply> queryOutboundCardList(HttpSession session,
            Page<OutboundCardApply> page, String name, String cardNo,
            String count, String deptNo) throws Exception {
        // 初始化分页信息
        Map<String, Object> paramMap = SqlUtil.buildPageMap(page);
        if (StrUtil.isNotEmpty(name)) {
            paramMap.put("name", name);
        }
        if (StrUtil.isNotEmpty(cardNo)) {
            paramMap.put("cardNo", cardNo);
        }
        paramMap.put("status", Constants.ACTIR_CARD_STOCK);
        paramMap.put("count", count);
        paramMap.put("deptNo", deptNo);
        page.setMap(paramMap);
        page.setTotal(Long.valueOf(count));
        // 查询待出卡单信息
        page = outboundCardApplyService.outboundAppliedList(page);

        return page;
    }

    // /**
    // * 查询方案信息
    // * @param codeType
    // * @param parentCode
    // * @return
    // * @throws Exception
    // */
    // @RequestMapping(value="/queryCardPlanList")
    // @ResponseBody
    // public Result queryCardPlanList(HttpSession session,String name,String
    // deptNo) throws Exception {
    // Result result = null;
    // try{
    // result = outboundCardApplyService.queryCardPlanList(name,"jhcard");
    // }catch(Exception e){
    // logger.info(e);
    // return Result.error(e.getMessage());
    // }
    // return result;
    // }
    /**
     * 查询方案信息
     * 
     * @param planNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryCardPlan")
    @ResponseBody
    public Map<String,Object> queryCardPlan(HttpSession session, String planNo)
            throws Exception {
        Map<String,Object> map = null;
        map = outboundCardApplyService.queryCardPlan(planNo);
        
        return map;
    }

    // /**
    // * 是否配置方案
    // * @param codeType
    // * @param parentCode
    // * @return
    // * @throws Exception
    // */
    // @RequestMapping(value="/checkDeployPlan")
    // @ResponseBody
    // public Result checkDeployPlan(HttpSession session,String name) throws
    // Exception {
    // Result result = null;
    // try{
    // result = outboundCardApplyService.queryCardPlanList(name,"jhcard");
    // }catch(Exception e){
    // logger.info(e);
    // return Result.error(e.getMessage());
    // }
    // return result;
    // }

//    /**
//     * 加载方案关联销售信息
//     * 
//     * @param model
//     * @param name
//     * @param cardNo
//     * @param count
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping(value = "/querySalesMen")
//    @ResponseBody
//    public List<Map<String, Object>> querySalesMenInfo(HttpSession session,
//            String planNo, String deptNo, String partnerNo) throws Exception {
//
//        // 加载此出单机构下业务员信息
//        List<Map<String, Object>> tradAgentList = outboundCardApplyService
//                .loadSalesMenData(deptNo, planNo, partnerNo);
//        return tradAgentList;
//    }

    /**
     * 保存关联销售信息
     * 
     * @param session
     * @param name
     * @param cardNo
     * @param count
     * @param deptNo
     * @param planNo
     * @param commamtFee
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/saveAgentRelaCardInfo")
    @ResponseBody
    public Result saveAgentRelaCardInfo(HttpSession session, String name,
            String cardNo, String count, String deptNo, String planNo,
            CommamtFee commamtFee) throws Exception {
        if (StrUtil.isEmpty(planNo)) {
            return Result.error(ActirationErrorInfo.OUT_1);
        }
        if (StrUtil.isEmpty(commamtFee.getOperatorNo())) {
            return Result.error(ActirationErrorInfo.OUT_2);
        }
        Result result = null;
        GatewayUser user = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        commamtFee.setOperatorDeptNo(user.getUserComcode());
        commamtFee.setOperator(user.getUserCode());
        commamtFee.setHandleTotal(Integer.parseInt(count));
        result = outboundCardApplyService.saveAgentRelaCardInfo(name, cardNo,
                Constants.ACTIR_CARD_STOCK, count, deptNo, planNo, commamtFee);
        return result;
    }

    /**
     * 返回出库申请页面
     * 
     * @param flag
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/successBack")
    public String successBack(HttpServletRequest request, String flag,
            String pricelessType) throws Exception {
        request.setAttribute("flag", flag);
        request.setAttribute("pricelessType", pricelessType);
        
        return "actirationCard/outboundApply/outbound";
    }

    @RequestMapping(value = "/queryOutboundDetail")
    public String queryOutboundDetail() throws Exception {

        return "actirationCard/outboundApply/outboundDetail";
    }

    /**
     * 出库申请记录查询
     * 
     * @param session
     * @param page
     * @param name
     * @param operatorNo
     * @param agengMan
     * @param startDate
     * @param endDate
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryCommamtFeeList")
    @ResponseBody
    public Page<CommamtFee> queryCommamtFeeList(HttpSession session,
            Page<CommamtFee> page, String name, String operatorName,
            String agentMan, String startDate, String endDate, String isPay)
                    throws Exception {

        // 初始化分页信息
        Map<String, Object> paramMap = SqlUtil.buildPageMap(page);
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        // String deptNo = gatewayuser.getDepartmentStr();
        // deptNo = "(" + deptNo + ")";
        String deptNo = gatewayuser.getUserComcode();
        if (StrUtil.isNotEmpty(name)) {
            paramMap.put("name", name);
        }
        if (StrUtil.isNotEmpty(operatorName)) {
            paramMap.put("operatorName", operatorName);
        }
        if (StrUtil.isNotEmpty(agentMan)) {
            paramMap.put("agentMan", agentMan);
        }
        if (StrUtil.isNotEmpty(startDate)) {
            paramMap.put("startDate", startDate);
        }
        if (StrUtil.isNotEmpty(endDate)) {
            paramMap.put("endDate", endDate);
        }
        if (StrUtil.isNotEmpty(isPay)) {
            paramMap.put("isPay", isPay);
        }
        paramMap.put("operator", gatewayuser.getUserCode());
        paramMap.put("operatorDeptNo", deptNo);
        page.setMap(paramMap);
        // 查询待出卡单信息
        page = outboundCardApplyService.queryCommamtFeeList(page);

        return page;
    }

    /**
     * 查询某条出库记录的明细
     * 
     * @param page
     * @param commamtId
     * @param count
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryCardInfoByCommamtId")
    @ResponseBody
    public Page<OutboundCardApply> queryCardInfoByCommamtId(
            Page<OutboundCardApply> page, String commamtId, String count,
            String cardDefineId) throws Exception {
        // 初始化分页信息
        Map<String, Object> paramMap = SqlUtil.buildPageMap(page);
        paramMap.put("commamtId", commamtId);
        paramMap.put("cardDefineId", cardDefineId);
        page.setTotal(Integer.parseInt(count));
        page.setMap(paramMap);
        page = outboundCardApplyService.queryCardInfoByCommamtId(page);
        return page;
    }

    @RequestMapping(value = "/queryCountMax")
    @ResponseBody
    public Result queryCountMax(HttpSession session, String name,
            String cardNo, String cardDefineId, String deptName, String planName)
            throws Exception {
        // 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        String deptNo = gatewayuser.getUserComcode();
        session.setAttribute("cardDefineName", name);
        session.setAttribute("deptName", deptName);
        session.setAttribute("planName", planName);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("cardDefineId", cardDefineId);
        map.put("cardNo", cardNo);
        map.put("status", Constants.ACTIR_CARD_STOCK);
        map.put("deptNo", deptNo);

        return outboundCardApplyService.queryCountMax(map);
    }

    /**
     * 缴费确认
     * 
     * @param commamtId
     * @param isPrefee
     * @param isPay
     * @return
     * @throws Exception
     */
   /* @RequestMapping(value = "/doConfirm")
    @ResponseBody
    public Result payConfirm(String commamtId, String isPreFee, String isPay)
            throws Exception {
        // 判断是否已收付
        // 传过来的收付标志
        String cpayMark = "X";
        // 传过来的收付流水号
        String ccavNo = "123";
        // 收付人和收付时间？
        if (StrUtil.isEmpty(cpayMark) || !"X".equals(cpayMark)) {
            // 还未收付，不可以做缴费确认
            return Result.error("尚未收付，不可以缴费确认！");
        } else {
            // 已收付可以缴费确认
            return outboundCardApplyService.doConfirm(commamtId, isPreFee,
                    isPay, cpayMark, ccavNo);
        }
    }
*/
    /**
     * 撤销出库
     * 
     * @param commamtId
     * @param isPrefee
     * @param isPay
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/doCancel")
    @ResponseBody
    public Result outboundApplyCancel(String commamtId,
            String isPay) throws Exception {
        HashMap<String,String> map=new HashMap<String,String>();
        map.put("payId", commamtId);
        FacadePayment payment = outboundCardApplyService.queryPayment(map);
        if (payment != null) {
            //如果是待支付或支付失败
            if(Constants.PAYMENT_STATUS_1.equals(payment.getStatus())
                    || Constants.PAYMENT_STATUS_3.equals(payment.getStatus())){
                //调用支付平台查询接口看是否支付完成
                payment = payService.noPaymentStatusForOut(payment);
                //如果支付平台接口查询为支付成功
                if(Constants.PAYMENT_STATUS_2.equals(payment.getStatus())){
                    // 已支付，不可以撤销出库
                    return Result.error("卡单已经缴费，不能撤销出库！");
                }
            } else if (Constants.PAYMENT_STATUS_2.equals(payment.getStatus())) {
                // 已支付，不可以撤销出库
                return Result.error("卡单已经缴费，不能撤销出库！");
            } else if (Constants.PAYMENT_STATUS_4.equals(payment.getStatus())) {
                // 已支付，不可以撤销出库
                return Result.error("服务器有点忙，请稍后再试！");
            }
        }
        
        // 未支付可以撤销出库
        return outboundCardApplyService
                .doCancel(commamtId, isPay);
    }

    /**
     * 取得打印内容
     * 
     * @param CommamtId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getPremamtAndAgentFee")
    @ResponseBody
    public Result queryPremamtAndAgentFee(HttpSession session, String commamtId)
            throws Exception {// 用户信息
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        return outboundCardApplyService.queryPremamtAndAgentFee(gatewayuser,
                commamtId);
    }

    /**
     * 归属渠道-渠道类型-新业务来源处理(根据codeType和上级code从数据字典中查询下级级联信息)
     * 
     * @param codeType
     * @param parentCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/loadSubCascadeList")
    @ResponseBody
    public List<DictDto> loadSubCascadeList(DictDto dict) throws Exception {
        List<DictDto> list = outboundCardApplyService.loadSubCascadeList(dict);
        return list;
    }

    /**
     * 选取旧业务来源
     * 
     * @param parentCode
     * @param newBsnsCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/chooseBsnsType")
    public @ResponseBody DictDto chooseBsnsType(String parentCode,
            String newBsnsCode) throws Exception {
        DictDto dd = new DictDto();
        if (StrUtil.isNotEmpty(parentCode) && StrUtil.isNotEmpty(newBsnsCode)) {
            List<DictDto> subDataList = DictCache.getDictDataByParentCode(
                    Constants.DICT_NEW_BUSINESS_SOURCE, parentCode);
            for (DictDto dictDto : subDataList) {
                if (newBsnsCode.equals(dictDto.getCode())) {
                    return dictDto;
                }
            }
        } else {
            dd.setOtherCode("");
        }
        return dd;
    }

    /**
     * 查询业务员-团队信息(从销管获取)
     * 
     * @param deptNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/querySauserAndTeamInfo")
    @ResponseBody
    public Result querySauserAndTeamInfo(String deptNo) throws Exception {
        if (StrUtil.isEmpty(deptNo)) {
            return Result.error("出单机构不能为空");
        }
        Result result = null;
        try {
            result = outboundCardApplyService.querySauserAndTeamInfo(deptNo);
        } catch (Exception e) {
            logger.info(e);
            return Result.error(e.getMessage());
        }
        return result;
    }

    /**
     * 查询服务代码信息(从销管获取)
     * 
     * @param deptNo
     * @param newBsnsType
     * @param channleCode_QD
     * @param empNo
     * @param agentNo
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryServiceNo")
    @ResponseBody
    public Result queryServiceNo(String deptNo, String newBsnsType,
            String channleCode_QD, String empNo, String agentNo)
            throws Exception {
        if (StrUtil.isEmpty(deptNo))
            return Result.error("出单机构不能为空");
        if (StrUtil.isEmpty(newBsnsType))
            return Result.error("业务来源不能为空");
        if (StrUtil.isEmpty(channleCode_QD))
            return Result.error("渠道名称不能为空");
        if (StrUtil.isEmpty(empNo))
            return Result.error("业务员代码不能为空");

        Result result = null;
        try {
            result = outboundCardApplyService.queryServiceNo(deptNo,
                    newBsnsType, channleCode_QD, empNo, agentNo);
        } catch (Exception e) {
            logger.info(e);
            return Result.error(e.getMessage());
        }
        return result;
    }

    /**
     * 查询中介-协议信息(从销管获取)
     * 
     * @param comCode
     * @param teamCode
     * @param businessSource
     * @param channelName
     * @param prodCode
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/queryAgentAndAgreeInfo")
    @ResponseBody
    public Result queryAgentAndAgreeInfo(String comCode, String teamCode,
            String businessSource, String channelName, String prodCode)
            throws Exception {
        if (StrUtil.isEmpty(comCode)) {
            return Result.error("出单机构不能为空");
        }
        if (StrUtil.isEmpty(teamCode)) {
            return Result.error("团队代码不能为空");
        }
        if (StrUtil.isEmpty(businessSource)) {
            return Result.error("业务来源不能为空");
        }
        if (StrUtil.isEmpty(channelName)) {
            return Result.error("渠道名称不能为空");
        }
        if (StrUtil.isEmpty(prodCode)) {
            return Result.error("产品代码不能为空");
        }

        Result result = null;
        try {
            result = outboundCardApplyService.queryAgentAndAgreeInfo(comCode,
                    teamCode, businessSource, channelName, prodCode);
        } catch (Exception e) {
            logger.info(e);
            return Result.error(e.getMessage());
        }
        return result;
    }
    
    /**
     * 回传收付缴费信息
     * @param session
     * @param commamtId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/backPay")
    @ResponseBody
    public Result backPay(HttpSession session, String commamtId)
            throws Exception {
        if (StrUtil.isEmpty(commamtId)) {
            return Result.error("出库ID不能为空");
        }
        CommamtFee commamtFee = outboundCardApplyService.queryForPay(commamtId);
        if (!Constants.ACTIR_CARD_OUTBOUND_PAY.equals(
                commamtFee.getStatus())) {
            return Result.error("出库ID为"+commamtId+"的出库信息还未缴费，不能回传收付缴费信息！");
        } else if ("1".equals(commamtFee.getBackPayFlag())) {//回传收付处理中
                return Result.error("出库ID为"+commamtId+"的记录正在回传收付处理中，请稍后重新查询");
            
        } else if ("2".equals(commamtFee.getBackPayFlag())) {//回传收付成功
                return Result.error("出库ID为"+commamtId+"的记录已回传收付成功,请重新查询");
        }
        GatewayUser gatewayuser = (GatewayUser) session
                .getAttribute(Constants.SESSION_USER);
        HashMap<String,String> map=new HashMap<String,String>();
        map.put("payId", commamtId);
        FacadePayment payment=outboundCardApplyService.queryPayment(map);
        if(payment==null){
        	payment=new FacadePayment();
        	FacadeNewPayment newPayment = outboundNewPayService.queryNewPayment(map);
        	payment.setPayId(newPayment.getPayId());
        	payment.setPaymentType(newPayment.getPayType());
        	payment.setTransAmt(newPayment.getAmount());
        	payment.setTransNo(newPayment.getRdSeq());
        	payment.setComCode(newPayment.getApplyEntity());
        }
        Result result = cardService.cardPayToPayment(payment,
                gatewayuser.getEmployeeNo(), gatewayuser.getUserCode());
        if ("success".equals(result.getResult())) {
            //更新卡单表
            payService.updateStatusByCommamtId(payment.getPayId(),
                    Constants.ACTIR_CARD_RELATION,
                    Constants.ACTIR_CARD_ACTIVABLE);
        }
        
        return result;
    }
}
